class ProductsController < ApplicationController
  layout :enable_layout

  def index
    @products = Product.order(created_at: :desc).all
  end

  def new
    @product = Product.new
    render "products/2016/new.html.slim"
  end

  def success
    render "products/2016/success.html.slim"
  end

  def create
    innoaward = Innoaward.find_by_year(Date.today.year)
    @product = Product.new(product_params)
    if @product.save
      # InnoawardMailer.new_product_success(@product).deliver_now
      InnoawardsProduct.create(innoaward_id: innoaward.id, product_id: @product.id)
      render json: @product, status: :created, location: @product
    else
      render json: @product.errors.full_messages, status: :unprocessable_entity
    end
  end

  def show
    current_year = available_years.include?(params[:year]) ? params[:year] : available_years.last
    @product = Product.find(params[:id])
    @award = Award.find(params[:award_id])
    @rank = Rank.where(product_id: @product.id, award_id: @award.id).first
    @other_products = @award.products.where.not(id: @product.id).order('ranks.vote')
    # @product.sync_to_product_a
    render "products/#{current_year}/show.html.slim"
  end

  # def edit
  #   @product = Product.find(params[:id])
  # end
  #
  # def update
  #   @product = Product.find(params[:id])
  #   @product.update(product_params)
  #   redirect_to product_path(@product)
  # end
  #
  # def destroy
  #   @product = Product.find(params[:id])
  #   @product.destroy
  #   redirect_to products_path
  # end

  private

  def product_params
    recommended_platform = params[:product][:recommended_platform]
    params[:product][:recommended_platform] = recommended_platform.split(',').map(&:strip) if (params[:product] && (recommended_platform.is_a? String))
    params
      .require(:product)
      .permit(:name, :logo, :logo_cache, :summary, :description, :note, :url, {screenshots: []},
              :published_at, :weibo, :wechat, :category, {recommended_platform: []},
              :c_name, :c_corp, :c_position, :c_corp_addr, :c_email, :c_mobile, :evaluation)
  end

end
